<template>
  <a-spin :spinning='confirmLoading'>
    <a-tabs defaultActiveKey='1'>
      <a-tab-pane tab='1、基本信息' key='1'></a-tab-pane>
    </a-tabs>
    <j-form-container :disabled='formDisabled'>
      <!-- 主表单区域 -->
      <a-form :form='form' slot='detail'>
        <a-row>
          <a-col :span='8'>
            <a-form-item label='合同编号' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <a-input
                v-decorator="['num', validatorRules.num]"
                :disabled="classifyShowInput != 'busSales'"
                placeholder='系统自动生成'
              ></a-input>
            </a-form-item>
            <!-- :disabled="formData.extendUrlParams.audit == 'preSale'" -->
          </a-col>
          <a-col :span='8'>
            <a-form-item label='合同名称' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <j-popup
                placeholder='请点击选择合同名称'
                v-decorator="['projectName', validatorRules.projectName]"
                :trigger-change='true'
                org-fields='id,project_name,customer_name,project_charger,bid_quote,gross_profit'
                dest-fields='bidProjectId,projectName,customerName,salesman,money,grossProfit'
                code='bid_project_select'
                @callback='projectNamePopupCallback'
                :disabled="
                  model.bpmStatus == '3' ||
                  classifyShowInput == 'preSale' ||
                  classifyShowInput == 'busSales' ||
                  classifyShowInput == 'gm' ||
                  classifyShowInput
                "
              />
              <a-input v-decorator="['bidProjectId']" v-show='false'></a-input>
            </a-form-item>
          </a-col>

          <a-col :span='8'>
            <a-form-item label='客户名称' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <a-input v-decorator="['customerName']" placeholder='可选择项目名称自动带入' disabled></a-input>
            </a-form-item>
          </a-col>

          <a-col :span='8'>
            <a-form-item label='销售经理' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <j-select-user-by-dep
                :multi='false'
                v-decorator="['salesman', validatorRules.salesman]"
                :disabled="
                  model.bpmStatus == '3' ||
                  classifyShowInput == 'preSale' ||
                  classifyShowInput == 'busSales' ||
                  classifyShowInput == 'gm' ||
                  classifyShowInput
                "
              />
            </a-form-item>
          </a-col>
          <a-col :span='8'>
            <a-form-item label='项目经理' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <j-select-user-by-dep
                :multi='false'
                v-decorator="['projectManager', validatorRules.projectManager]"
                :disabled="
                 ( model.bpmStatus == '3' ||
                  classifyShowInput == 'preSale' ||
                  classifyShowInput == 'busSales' ||
                  classifyShowInput == 'gm' ||
                  classifyShowInput)&&!clickChangeCharger
                "
              />
            </a-form-item>
          </a-col>
          <a-col :span='8'>
            <a-form-item label='售前经理' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <j-select-user-by-dep
                :multi='false'
                v-decorator="['preSaleLeader', validatorRules.preSaleLeader]"
                :disabled="
                  model.bpmStatus == '3' ||
                  classifyShowInput == 'preSale' ||
                  classifyShowInput == 'busSales' ||
                  classifyShowInput == 'gm' ||
                  classifyShowInput
                "
              />
            </a-form-item>
          </a-col>
          <a-col :span='8'>
            <a-form-item label='合同类型' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <j-dict-select-tag
                type='list'
                v-decorator="['type', validatorRules.type]"
                :trigger-change='true'
                dictCode='icm_contract_sale_type'
                placeholder='请选择合同类型'
                :disabled="
                  model.bpmStatus == '3' ||
                  classifyShowInput == 'preSale' ||
                  classifyShowInput == 'busSales' ||
                  classifyShowInput == 'gm' ||
                  classifyShowInput
                "
              />
            </a-form-item>
          </a-col>
          <a-col :span='8'>
            <a-form-item label='合同分类' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <j-dict-select-tag
                type='list'
                v-decorator="['classify', validatorRules.classify]"
                :trigger-change='true'
                dictCode='icm_contract_sale_classify'
                placeholder='请选择合同分类'
                :disabled="
                  model.bpmStatus == '3' ||
                  classifyShowInput == 'preSale' ||
                  classifyShowInput == 'busSales' ||
                  classifyShowInput == 'gm' ||
                  classifyShowInput
                "
              />
            </a-form-item>
          </a-col>
          <a-col :span='8'>
            <a-form-item label='合同金额' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <a-input
                v-decorator="['money', validatorRules.money]"
                placeholder='请输入合同金额'
                style='width: 100%'
                :min='0'
                type='number'
                :disabled="
                  model.bpmStatus == '3' ||
                  classifyShowInput == 'preSale' ||
                  classifyShowInput == 'busSales' ||
                  classifyShowInput == 'gm' ||
                  classifyShowInput
                "
              >
                <span slot='addonAfter'>元</span>
              </a-input>
            </a-form-item>
          </a-col>
          <a-col :span='8'>
            <a-form-item label='税费' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <a-input
                v-decorator="['taxation', validatorRules.taxation]"
                placeholder='请输入税费'
                style='width: 100%'
                :min='0'
                type='number'
                :disabled="
                  model.bpmStatus == '3' ||
                  classifyShowInput == 'preSale' ||
                  classifyShowInput == 'busSales' ||
                  classifyShowInput == 'gm' ||
                  classifyShowInput
                "
              >
                <span slot='addonAfter'>元</span>
              </a-input>
            </a-form-item>
          </a-col>
          <a-col :span='8'>
            <a-form-item label='中标服务费' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <a-input
                v-decorator="['bidServiceCharge', validatorRules.bidServiceCharge]"
                placeholder='请输入中标服务费'
                style='width: 100%'
                :min='0'
                type='number'
                :disabled="
                  model.bpmStatus == '3' ||
                  classifyShowInput == 'preSale' ||
                  classifyShowInput == 'busSales' ||
                  classifyShowInput == 'gm' ||
                  classifyShowInput
                "
              >
                <span slot='addonAfter'>元</span>
              </a-input>
            </a-form-item>
          </a-col>
          <!-- <a-col :span="8">
            <a-form-item label="销售毛利" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input
                v-decorator="['saleGrossProfit', validatorRules.saleGrossProfit]"
                placeholder="请输入销售毛利"
                style="width: 100%"
                :min="0"
                type="number"
                :disabled="
                  model.bpmStatus == '3' ||
                  classifyShowInput == 'preSale' ||
                  classifyShowInput == 'busSales' ||
                  classifyShowInput == 'gm' ||
                  classifyShowInput
                "
              >
                <span slot="addonAfter">元</span>
              </a-input>
            </a-form-item>
          </a-col> -->
          <a-col :span='8'>
            <a-form-item label='付款方式' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <a-input
                v-decorator="['paymentMethod', validatorRules.paymentMethod]"
                placeholder='请输入付款方式'
                :disabled="
                  model.bpmStatus == '3' ||
                  classifyShowInput == 'preSale' ||
                  classifyShowInput == 'busSales' ||
                  classifyShowInput == 'gm' ||
                  classifyShowInput
                "
              ></a-input>
            </a-form-item>
          </a-col>

          <!--          <a-col :span="8" >-->
          <!--            <a-form-item label="商机名称" :labelCol="labelCol" :wrapperCol="wrapperCol">-->
          <!--              <j-popup-->
          <!--                placeholder='请点击选择商机名称'-->
          <!--                v-decorator="['opportunityName', validatorRules.opportunityName]"-->
          <!--                :trigger-change="true"-->
          <!--                org-fields="id,name"-->
          <!--                dest-fields="opportunityId,opportunityName"-->
          <!--                code="bus_business_opportunity_select"-->
          <!--                @callback="popupCallback"-->
          <!--              />-->
          <!--              <a-input v-decorator="['opportunityId']" v-show='false'></a-input>-->
          <!--            </a-form-item>-->
          <!--          </a-col>-->

          <a-col :span='8'>
            <a-form-item label='质保时长' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <a-input
                v-decorator="['warrantyDay', validatorRules.warrantyDay]"
                placeholder='请输入质保时长'
                :disabled="
                  model.bpmStatus == '3' ||
                  classifyShowInput == 'preSale' ||
                  classifyShowInput == 'busSales' ||
                  classifyShowInput == 'gm' ||
                  classifyShowInput
                "
              ></a-input>
            </a-form-item>
          </a-col>
          <div v-has="'ContractSale:ratis'" v-if="model.bpmStatus !== '1' && model.bpmStatus">
            <a-col :span='8'>
              <a-form-item label='价值比' :labelCol='labelCol' :wrapperCol='wrapperCol'>
                <a-input v-decorator="['commissionRatisA']" :disabled="classifyShowInput != 'preSale'"></a-input>
              </a-form-item>
            </a-col>
<!--            <a-col :span='8'>-->
<!--              <a-form-item label='提成系数B' :labelCol='labelCol' :wrapperCol='wrapperCol'>-->
<!--                <a-input v-decorator="['commissionRatisB']" :disabled="classifyShowInput != 'preSale'"></a-input>-->
<!--              </a-form-item>-->
<!--            </a-col>-->
<!--            <a-col :span='8'>-->
<!--              <a-form-item label='提成系数C' :labelCol='labelCol' :wrapperCol='wrapperCol'>-->
<!--                <a-input v-decorator="['commissionRatisC']" :disabled="classifyShowInput != 'preSale'"></a-input>-->
<!--              </a-form-item>-->
<!--            </a-col>-->
<!--            <a-col :span='8'>-->
<!--              <a-form-item label='提成系数D' :labelCol='labelCol' :wrapperCol='wrapperCol'>-->
<!--                <a-input v-decorator="['commissionRatisD']" :disabled="classifyShowInput != 'preSale'"></a-input>-->
<!--              </a-form-item>-->
<!--            </a-col>-->
          </div>

          <a-col :span='8'>
            <a-form-item label='附件' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <j-upload
                v-decorator="['accessories', validatorRules.accessories]"
                :trigger-change='true'
                :disabled="
                  model.bpmStatus == '3' ||
                  classifyShowInput == 'preSale' ||
                  classifyShowInput == 'busSales' ||
                  classifyShowInput == 'gm' ||
                  classifyShowInput
                "
              ></j-upload>
            </a-form-item>
          </a-col>
          <a-col :span='8'>
            <a-form-item label='预计毛利' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <a-input v-decorator="['grossProfit']" disabled></a-input>
            </a-form-item>
          </a-col>
          <a-col :span='8'>
            <a-form-item label='实际毛利' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <a-input v-decorator="['actualProfit']" disabled></a-input>
            </a-form-item>
          </a-col>

          <a-col :span='24'>
            <a-form-item label='备注' :labelCol='labelCol2' :wrapperCol='wrapperCol2'>
              <a-textarea
                v-decorator="['remarks']"
                rows='3'
                placeholder='请输入备注'
                :disabled="
                  model.bpmStatus == '3' ||
                  classifyShowInput == 'preSale' ||
                  classifyShowInput == 'busSales' ||
                  classifyShowInput == 'gm' ||
                  classifyShowInput
                "
              />
            </a-form-item>
          </a-col>
          <div v-if="model.archived == 'N' && model.bpmStatus === '3'">
            <div v-has="'ContractSale:archive'">
              <a-col :span='8'>
                <a-form-item label='签订日期' :labelCol='labelCol' :wrapperCol='wrapperCol'>
                  <j-date
                    placeholder='请选择签订日期'
                    v-decorator="['signDate', validatorRules.signDate]"
                    :trigger-change='true'
                    style='width: 100%'
                    :disabled='this.clickChangeCharger'
                  />
                </a-form-item>
              </a-col>
              <a-col :span='8'>
                <a-form-item label='是否归档' :labelCol='labelCol' :wrapperCol='wrapperCol'>
                  <j-switch v-decorator="['archived', validatorRules.archived]"
                            :disabled='this.clickChangeCharger'></j-switch>
                </a-form-item>
              </a-col>
              <a-col :span='8'>
                <a-form-item label='归档文件' :labelCol='labelCol' :wrapperCol='wrapperCol'>
                  <j-upload v-decorator="['archiveFile', validatorRules.archiveFile]" :trigger-change='true'
                            :disabled='this.clickChangeCharger'></j-upload>
                </a-form-item>
              </a-col>
            </div>
          </div>
          <div v-else-if="model.bpmStatus === '3' && model.archived == 'Y'">
            <a-col :span='8'>
              <a-form-item label='签订日期' :labelCol='labelCol' :wrapperCol='wrapperCol'>
                <j-date
                  placeholder='请选择签订日期'
                  v-decorator="['signDate', validatorRules.signDate]"
                  :trigger-change='true'
                  style='width: 100%'
                  :disabled='this.clickChangeCharger'
                />
              </a-form-item>
            </a-col>
            <a-col :span='8'>
              <a-form-item label='是否归档' :labelCol='labelCol' :wrapperCol='wrapperCol'>
                <j-switch v-decorator="['archived', validatorRules.archived]"
                          :disabled='this.clickChangeCharger'></j-switch>
              </a-form-item>
            </a-col>
            <a-col :span='8'>
              <a-form-item label='归档文件' :labelCol='labelCol' :wrapperCol='wrapperCol'>
                <j-upload v-decorator="['archiveFile', validatorRules.archiveFile]" :trigger-change='true'
                          :disabled='this.clickChangeCharger'></j-upload>
              </a-form-item>
            </a-col>
          </div>
        </a-row>
      </a-form>
    </j-form-container>

    <!-- 子表单区域 -->
    <a-tabs v-model='activeKey' @change='handleChangeTabs'>
      <a-tab-pane tab='2、回款计划' :key='refKeys[0]' :forceRender='true'>
        <j-editable-table
          :ref='refKeys[0]'
          :loading='contractSalePaymentCollectionTable.loading'
          :columns='contractSalePaymentCollectionTable.columns'
          :dataSource='contractSalePaymentCollectionTable.dataSource'
          :maxHeight='300'
          :disabled="
            formDisabled ||
            classifyShowInput == 'preSale' ||
            classifyShowInput == 'busSales' ||
            classifyShowInput == 'gm' ||
            model.bpmStatus === '3' ||
            classifyShowInput
          "
          :rowNumber='true'
          :rowSelection='true'
          :actionButton='true'
        />
      </a-tab-pane>
    </a-tabs>
    <ContractBidProjectDetailList
      :mainId='bidProjectId || model.bidProjectId'
      :index='3'
    ></ContractBidProjectDetailList>
    <ContractSalePurchaseApplyDetail
      :list='purchaseDetailList'
      v-if="model.id && model.bpmStatus == '3'"
      :index='4'
    ></ContractSalePurchaseApplyDetail>
    <ContractSalePurchaseContractDetail
      :list='purchaseContractList'
      v-if="model.id && model.bpmStatus == '3'"
      :index='5'
    ></ContractSalePurchaseContractDetail>
    <ContractSaleMoneyFlow
      :index='6'
      :contractActualReturnMoney='contractActualReturnMoney'
      :contractActualPaymentMoney='contractActualPaymentMoney'
      :moneyFlow='+contractActualReturnMoney - +contractActualPaymentMoney'
      v-if="model.id && model.bpmStatus == '3'"
    ></ContractSaleMoneyFlow>
    <!--    <Test ref='testForm'></Test>-->
    <a-row v-if='showFlowSubmitButton' style='text-align: center; width: 100%; margin-top: 16px'>
      <a-button @click='handleOk' type='primary'>提 交</a-button>
    </a-row>
  </a-spin>
</template>

<script>
import pick from 'lodash.pick'
import { getAction, httpAction } from '@/api/manage'
import { FormTypes, getRefPromise, VALIDATE_NO_PASSED, validateFormAndTables } from '@/utils/JEditableTableUtil'
import { JEditableTableMixin } from '@/mixins/JEditableTableMixin'
import { validateDuplicateValue } from '@/utils/util'
import ContractBidProjectDetailList from './ContractBidProjectDetailList'
import ContractSalePurchaseApplyDetail from './ContractSalePurchaseApplyDetail'
import ContractSalePurchaseContractDetail from './ContractSalePurchaseContractDetail'
import ContractSaleMoneyFlow from './ContractSaleMoneyFlow'
import { toFixedTwo } from '@/utils/util'

export default {
  name: 'ContractSaleForm',
  mixins: [JEditableTableMixin],
  components: {
    ContractBidProjectDetailList,
    ContractSalePurchaseApplyDetail,
    ContractSalePurchaseContractDetail,
    ContractSaleMoneyFlow
  },
  data() {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      labelCol2: {
        xs: { span: 24 },
        sm: { span: 2 }
      },
      wrapperCol2: {
        xs: { span: 24 },
        sm: { span: 22 }
      },
      // 新增时子表默认添加几行空数据
      addDefaultRowNum: 1,
      validatorRules: {
        archiveFile: {
          rules: [{ required: true, message: '请上传归档文件!' }]
        },
        archived: {
          rules: [{ required: true, message: '请选择归档状态!' }]
        },
        signDate: {
          rules: [{ required: true, message: '请输入签订日期!' }]
        },
        projectName: {
          rules: [{ required: true, message: '请点击选择项目' }]
        },
        money: {
          rules: [
            { required: true, message: '请输入合同金额!' },
            { pattern: /^(([0-9]*)|([0]\.\d{0,4}|[0-9]*\.\d{0,4}))$/, message: '请输入正确的合同金额!' }
          ]
        },
        taxation: {
          rules: [
            { required: true, message: '请输入税费!' },
            { pattern: /^(([0-9]*)|([0]\.\d{0,4}|[0-9]*\.\d{0,4}))$/, message: '请输入正确的税费金额!' }
          ]
        },
        bidServiceCharge: {
          rules: [
            { required: true, message: '请输入中标服务费!' },
            { pattern: /^(([0-9]*)|([0]\.\d{0,4}|[0-9]*\.\d{0,4}))$/, message: '请输入正确的中标服务费!' }
          ]
        },
        paymentMethod: {
          rules: [{ required: true, message: '请输入付款方式!' }]
        },
        projectManager: {
          rules: [{ required: true, message: '请选择项目经理!' }]
        },
        preSaleLeader: {
          rules: [{ required: true, message: '请选择售前负责人!' }]
        },
        salesman: {
          rules: [{ required: true, message: '请选择销售人员!' }]
        },
        type: {
          rules: [{ required: true, message: '请选择合同类型!' }]
        },
        classify: {
          rules: [{ required: true, message: '请选择合同分类!' }]
        },
        saleGrossProfit: {
          rules: [
            { required: true, message: '请输入销售毛利!' },
            { pattern: /^(([0-9]*)|([0]\.\d{0,4}|[0-9]*\.\d{0,4}))$/, message: '请输入正确的金额!' }
          ]
        },
        warrantyDay: {
          rules: [{ required: true, message: '请输入质保时长!' }]
        },
        accessories: {
          rules: [{ required: true, message: '请点击上传附件!' }]
        },
        opportunityName: {
          rules: [{ required: true, message: '请点击选择商机名称!' }]
        }
      },
      refKeys: ['contractSalePaymentCollection'],
      tableKeys: ['contractSalePaymentCollection'],
      activeKey: 'contractSalePaymentCollection',
      // 销售合同-回款管理
      contractSalePaymentCollectionTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '回款条件',
            required: true,
            key: 'returnCondition',
            type: FormTypes.select,
            dictCode: 'icm_payment_collection_condition',
            placeholder: '请选择',
            defaultValue: '',
            width: '13%',
            validateRules: [{ required: true, message: '${title}不能为空' }]
          },
          {
            title: '计划回款金额(元)',
            required: true,
            key: 'expectMoney',
            type: FormTypes.inputNumber,
            placeholder: '请输入${title}',
            defaultValue: '',
            width: '14%',
            validateRules: [{ required: true, pattern: 'money', message: '${title}不能为空' }]
          },
          {
            title: '计划回款时间',
            required: true,
            key: 'expectTime',
            type: FormTypes.date,
            placeholder: '请选择',
            defaultValue: '',
            width: '12%',
            validateRules: [{ required: true, message: '${title}不能为空' }]
          },
          {
            title: '是否开票',
            key: 'billing',
            type: FormTypes.select,
            dictCode: 'switch_status',
            placeholder: '请输入${title}',
            defaultValue: '否',
            width: '7%'
          },
          {
            title: '开票比例',
            key: 'billingRatio',
            type: FormTypes.inputNumber,
            placeholder: '请输入${title}',
            defaultValue: '',
            width: '7%',
            validateRules: [{ pattern: 'n', message: '${title}格式不正确' }]
          },
          {
            title: '回款负责人',
            required: true,
            key: 'paymantCharger',
            type: FormTypes.sel_user,
            placeholder: '请输入${title}',
            defaultValue: '',
            validateRules: [{ required: true, message: '${title}不能为空' }]
          }
        ]
      },
      url: {
        add: '/contract/contractSale/add',
        edit: '/contract/contractSale/edit',
        queryById: '/contract/contractSale/queryById',
        contractSalePaymentCollection: {
          list: '/contract/contractSale/queryContractSalePaymentCollectionByMainId'
        },
        purchaseDetailList: '/contract/contractPurchaseApply/nonPermissionList',
        purchaseContractList: '/contract/contractPurchase/nonPermissionList'
      },
      bidProjectId: '',
      purchaseDetailList: [],
      purchaseContractList: [],
      fields: [
        'num',
        'money',
        'paymentMethod',
        'salesman',
        'signDate',
        'type',
        'classify',
        'saleGrossProfit',
        'taxation',
        'bidServiceCharge',
        'warrantyDay',
        'accessories',
        'opportunityId',
        'opportunityName',
        'bpmStatus',
        'remarks',
        'bidProjectId',
        'projectName',
        'archived',
        'archiveFile',
        'projectManager',
        'preSaleLeader',
        'customerName',
        'commissionRatisA',
        'commissionRatisB',
        'commissionRatisC',
        'commissionRatisD',
        'grossProfit',
        'actualProfit',
        'clickArchive',
        'clickChangeCharger'
      ],
      contractActualReturnMoney: 0,
      contractActualPaymentMoney: 0,
      clickChangeCharger: false
    }
  },
  props: {
    //流程表单data
    formData: {
      type: Object,
      default: () => {
      },
      required: false
    },
    //表单模式：false流程表单 true普通表单
    formBpm: {
      type: Boolean,
      default: false,
      required: false
    },
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  computed: {
    formDisabled() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return false
        }
        return true
      }
      return this.disabled
    },
    showFlowSubmitButton() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return true
        }
      }
      return false
    },
    classifyShowInput() {
      if (this.formBpm === true) {
        if (this.formData.extendUrlParams) {
          if (this.formData.extendUrlParams.audit == 'preSale') {
            return 'preSale'
          }
          if (this.formData.extendUrlParams.audit == 'busSales') {
            return 'busSales'
          }
          if (this.formData.extendUrlParams.audit == 'gm') {
            return 'gm'
          }
        }
      }
      return false
    }
  },
  watch: {
    'model.id': {
      immediate: true,
      handler(value) {
        if (value) {
          this.queryPurchaseDetail(value)
        }
      },
    },
    '$store.state.bpm.bpmSubmitStates': {
      immediate: true,
      handler(val) {
        if (val && val.edit && val.edit === '1') {
          this.handleOk().then(res => {
            if (res) {
              this.$store.commit('BPM_SUBMIT_STATES', { edit: '2' })
            }
          })
        }
      }
    },
    'model.bpmStatus': {
      immediate: true,
      handler(value) {
        let res = this.contractSalePaymentCollectionTable.columns.some((item) => {
          return item.key == 'actualMoney'
        })
        if (value == '3') {
          if (!res) {
            this.contractSalePaymentCollectionTable.columns.push(
              {
                title: '实际回款金额(元)',
                key: 'actualMoney',
                width: '13%',
                type: FormTypes.inputNumber,
                placeholder: '无'
              },
              {
                title: '实际回款时间',
                key: 'actualTime',
                width: '12%',
                placeholder: '无',
                type: FormTypes.date
              }
            )
          }
        } else {
          this.contractSalePaymentCollectionTable.columns.forEach((v, i) => {
            if (v.key == 'actualMoney') {
              this.contractSalePaymentCollectionTable.columns.splice(i, 1)
            }
          })
          this.contractSalePaymentCollectionTable.columns.forEach((v, i) => {
            if (v.key == 'actualTime') {
              this.contractSalePaymentCollectionTable.columns.splice(i, 1)
            }
          })
        }
      }
    },
    'contractSalePaymentCollectionTable.dataSource': {
      deep: true,
      handler(value) {
        let total = 0
        value.forEach((v) => {
          if (v.actualMoney) {
            total += v.actualMoney
          }
        })
        this.contractActualReturnMoney = toFixedTwo(total) || 0
      }
    },
    purchaseContractList: {
      deep: true,
      handler(value) {
        let total = 0
        value.forEach((v) => {
          v[0].contractPurchasePaymentList.forEach((val) => {
            total += val.actualMoney
          })
        })
        this.contractActualPaymentMoney = toFixedTwo(total) || 0

      }
    }
  },
  created() {
    //如果是流程中表单，则需要加载流程表单data
    this.showFlowData()
  },
  mounted() {
  },
  methods: {
    handleOk() {
      const that = this
      return new Promise(((resolve, reject) => {
        /** 触发表单验证 */
        this.getAllTable().then(tables => {
          /** 一次性验证主表和所有的次表 */
          return validateFormAndTables(this.form, tables)
        }).then(allValues => {
          if (typeof this.classifyIntoFormData !== 'function') {
            throw this.throwNotFunction('classifyIntoFormData')
          }
          let formData = this.classifyIntoFormData(allValues)
          // 发起请求
          let url = this.url.add, method = 'post'
          if (this.model.id) {
            url = this.url.edit
            method = 'put'
          }
          that.confirmLoading = true
          httpAction(url, formData, method).then((res) => {
            if (res.success) {
              that.$message.success(res.message)
              that.$emit('ok')
              resolve(true)
              that.close()
            } else {
              that.$message.warning(res.message)
            }
          }).finally(() => {
            that.confirmLoading = false
          })
          // return this.request(formData)
        }).catch(e => {
          this.$store.commit('BPM_SUBMIT_STATES', {})
          if (e.error === VALIDATE_NO_PASSED) {
            // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
            this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
          } else {
            console.error(e)
          }
        })
      }))

    },
    queryPurchaseDetail(value) {
      getAction(this.url.purchaseDetailList, { saleId: value, pageNo: -1, pageSize: -1 }).then((res) => {
        if (res.success) {
          let data = []
          res.result.records.forEach((v, i) => {
            data.push(res.result.records.slice(i, i + 1))
          })
          this.purchaseDetailList = data
        }
      })
      getAction(this.url.purchaseContractList, { saleId: value, pageNo: -1, pageSize: -1 }).then((res) => {
        if (res.success) {
          let data = []
          res.result.records.forEach((v, i) => {
            data.push(res.result.records.slice(i, i + 1))
          })
          this.purchaseContractList = data
        }
      })
    },
    addBefore() {
      this.form.resetFields()
      this.contractSalePaymentCollectionTable.dataSource = []
    },
    getAllTable() {
      let values = this.tableKeys.map((key) => getRefPromise(this, key))
      return Promise.all(values)
    },
    /** 调用完edit()方法之后会自动调用此方法 */
    editAfter() {
      let fieldval = pick(this.model, this.fields)
      if (fieldval.clickArchive) {
        if (!fieldval.signDate) {
          fieldval.signDate = this.getNowDate()
        }
      }
      if (fieldval.clickChangeCharger) {
        this.clickChangeCharger = true
      }
      this.$nextTick(() => {
        this.form.setFieldsValue(fieldval)
      })
      // 加载子表数据
      if (this.model.id) {
        let params = { id: this.model.id }
        this.requestSubTableData(
          this.url.contractSalePaymentCollection.list,
          params,
          this.contractSalePaymentCollectionTable
        )
      }
    },
    getNowDate() {
      let date = new Date()
      let res = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate()
      return res
    },
    /** 整理成formData */
    classifyIntoFormData(allValues) {
      let main = Object.assign(this.model, allValues.formValue)
      return {
        ...main, // 展开
        contractSalePaymentCollectionList: allValues.tablesValue[0].values
      }
    },
    //渲染流程表单数据
    showFlowData() {
      if (this.formBpm === true) {
        let params = { id: this.formData.dataId }
        getAction(this.url.queryById, params).then((res) => {
          if (res.success) {
            this.edit(res.result)
          }
        })
      }
    },
    validateError(msg) {
      this.$message.error(msg)
    },
    projectNamePopupCallback(row) {
      this.bidProjectId = row.bidProjectId
      this.form.setFieldsValue(pick(row, this.fields))
    },
    popupCallback(row) {
      this.form.setFieldsValue(pick(row, this.fields))
    }
  }
}
</script>
<style scoped>
</style>